<template>
  <div class="zy-content" style="margin-bottom: 0">
    <div class="searchBox search-box-layout">
      <search :columns="searchData" @getSearch="getSearch(arguments)"></search>
    </div>
    <div class="list-layout mt16">
      <div class="btns clear">
        <span class="title">{{ $t("common.listInformation") }}</span>
        <Button @click="handleAdd"> 新增</Button>
      </div>
      <div class="tableContent" :style="{ height: tableHeight + 'px' }">
        <el-table ref="table" :data="list" style="width: 100%" :height="tableHeight" row-key="id" border
                  @expand-change="handleExpandChange" emptyText="暂无数据" v-if="isTableVisible"
                  header-cell-style="tableHeaderColor">
          <el-table-column type="expand" align="center">
            <template slot-scope="scope">
              <div class="cil-table no-padding">
                <!--                子级 展开表-->
                <el-table ref="tableCil" border size="small" :data="scope.row.children" emptyText="暂无数据">
                  <el-table-column type="index" width="50" label="序号" align="center"/>
                  <el-table-column label="产品名称" prop="productId" min-width="150" align="center" show-overflow-tooltip>
                    <template slot-scope="scope">
                      <span>{{
                          productData.find((i) => i.id === scope.row.productId)
                              ?.productName
                        }}</span>
                    </template>
                  </el-table-column>
                  <el-table-column label="工艺路线名称" prop="processRouteId" min-width="150" align="center"
                                   show-overflow-tooltip>
                    <template slot-scope="scope">
                      <span>{{
                          allRouteData.find(
                              (i) => i.id === scope.row.processRouteId
                          )?.processName
                        }}</span>
                    </template>
                  </el-table-column>
                  <el-table-column label="物料名称" prop="bomId" min-width="150" align="center" show-overflow-tooltip>
                    <template slot-scope="scope">
                      <span>{{
                          materialData.find((i) => i.id === scope.row.bomId)
                              ?.materialBomName
                        }}</span>
                    </template>
                  </el-table-column>
                  <el-table-column label="数量" prop="planCount" min-width="150" align="center" show-overflow-tooltip/>
                  <el-table-column label="操作" prop="ops" min-width="100" align="center">
                    <template slot-scope="scope">
                      <Button size="small" class="operationBtn" @click="handleIssue(scope.row)"><i
                          class="iconfont zy-common-bianji"></i>下发
                      </Button>
                    </template>
                  </el-table-column>
                </el-table>
              </div>
            </template>
          </el-table-column>
          <el-table-column type="index" width="50" label="序号" align="center"/>
          <el-table-column label="计划号" prop="planNo" min-width="150" show-overflow-tooltip align="center">
          </el-table-column>
          <el-table-column label="计划开始时间" prop="planBeginTime" min-width="150" show-overflow-tooltip align="center"/>
          <el-table-column label="计划结束时间" prop="planEndTime" min-width="150" show-overflow-tooltip align="center"/>

          <el-table-column label="工厂/车间" prop="organizationId" min-width="150" show-overflow-tooltip align="center">
            <template slot-scope="scope">
              <span>{{
                  lineListAll.find((i) => i.id === scope.row.organizationId)
                      ?.orgName
                }}</span>
            </template>
          </el-table-column>
          <el-table-column label="计划状态" prop="status" min-width="150" show-overflow-tooltip align="center">
            <template slot-scope="scope">
              <span>{{
                  statusData.find((i) => i.value === scope.row.status)?.label
                }}</span>
            </template>
          </el-table-column>
          <el-table-column label="计划类型" prop="status" min-width="150" show-overflow-tooltip align="center">
            <template slot-scope="scope">
              <span>{{
                  typeData.find((i) => i.value === scope.row.type)?.label
                }}</span>
            </template>
          </el-table-column>
          <el-table-column label="实际开始时间" prop="actualBeginTime" min-width="150" show-overflow-tooltip align="center"/>
          <el-table-column label="实际结束时间" prop="actualEndTime" min-width="150" show-overflow-tooltip align="center"/>
          <el-table-column label="操作" min-width="200" align="center" fixed="right">
            <template slot-scope="scope">
              <Button size="small" class="operationBtn" :disabled="scope.row.status === 1"
                      @click="handleEditRow(scope.row)"><i class="iconfont zy-common-bianji"></i>编辑
              </Button>
              <Button size="small" class="operationBtn" :disabled="scope.row.status === 1"
                      @click="handleDeleteRow(scope.row)"><i class="iconfont zy-common-shanchu"></i>删除
              </Button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="pageWrap mt16">
        <pageLeftTitle :total="total"/>
        <Page :total="total" :page-size="params.pageSize" :current="params.current" @on-change="changePageNum"
              @on-page-size-change="changePageSize" show-sizer/>
      </div>
    </div>
    <Modal :mask-closable="false" v-model="deleteShow" title="删除" class="modal-title-layout">
      <div class="icon red">
        <i class="iconfont zy-common-shanchu"></i>
      </div>
      <p class="title">
        <span>{{ $t("common.sureDelete") }}</span>
      </p>
      <div slot="footer">
        <Button type="default" @click="deleteShow = false">取消</Button>
        <Button type="primary" @click="handleDeleteSure">确定</Button>
      </div>
    </Modal>
    `

    <CreateOrUpdateModal :visible="createStatus" :form="form" :title="form.id ? '编辑' : '新增'"
                         @update:visible="createStatus = $event" :handleAddSubmit="handleAddSubmit" :lineList="lineList"
                         :statusData="statusData" :typeData="typeData" :allRouteData="allRouteData"
                         :productData="productData"
                         :materialData="materialData" :keysArray="keysArray"/>
  </div>
</template>

<script>
import ImportExcelModal from "@/components/importExcel.vue";
import {buildTree} from "@/util";
import search from "@/components/curd/searchList.vue";
import toggleTableOperation from "@/mixins/toggleTableOperation";
import CreateOrUpdateModal from "./modal_open.vue";
import DrawerProcess from "./drawerProcess";

import {
  lineAll,
  editBaseDataPlanApi,
  addBaseDataPlanApi,
  deleteBaseDataPlanApi,
  productBaseDataPlanApi,
} from "@/api/production/productionPlan";
import {
  allRouteApi,
  productAllApi,
  materialBomApi,
  ProductionPlanDetailApi,
  addProductionPlanDetailApi,
  editProductionPlanDetailApi,
  deleteProductionPlanDetailApi,
  issuePlan,
} from "@/api/production/planDetail";

export default {
  name: "productionPlan",
  components: {ImportExcelModal, search, CreateOrUpdateModal, DrawerProcess},
  mixins: [toggleTableOperation],
  data() {
    return {
      isTableVisible: true,
      params: {
        pageSize: 20,
        current: 1,
      },
      searchData: [
        {
          title: "计划号",
          key: "productName",
        },
      ],
      statusData: [
        {label: "已下发", value: 1},
        {label: "未下发", value: 0},
      ],
      typeData: [
        {label: "销售计划", value: "1"},
        {label: "备库计划", value: "2"},
        {label: "返修计划", value: "3"},
      ],
      columns: [
        {
          title: "计划开始时间",
          key: "planBeginTime",
          width: 220,
          tree: true,
        },
        {
          title: "计划结束时间",
          key: "planEndTime",
          align: "center",
          width: 180,
          resizable: true,
        },
        {
          title: "计划号",
          key: "planNo",
          align: "center",
          width: 180,
          resizable: true,
        },
        {
          title: "工厂/车间",
          key: "organizationId",
          align: "center",
          width: 100,
          render: (h, params) => {
            const name = this.lineListAll.find(
                (i) => i.id === params.row.organizationId
            );
            return h("div", name.orgName);
          },
        },
        {
          title: "计划状态",
          key: "status",
          align: "center",
          width: 100,
          render: (h, params) => {
            const name = this.statusData.find(
                (i) => i.value === params.row.status
            );
            return h("div", name.label);
          },
        },
        {
          title: "实际开始时间",
          key: "actualBeginTime",
          align: "center",
          width: 180,
        },
        {
          title: "实际结束时间",
          key: "actualEndTime",
          align: "center",
          width: 180,
        },
        {
          title: "计划类型",
          key: "type",
          align: "center",
          width: 100,
          render: (h, params) => {
            const name = this.typeData.find((i) => i.value === params.row.type);
            return h("div", name.label);
          },
        },
        {
          title: "操作",
          slot: "action",

          width: 250,
          align: "center",
        },
      ],
      importExcelState: false,
      list: [],
      total: 0,
      deleteShow: false,
      currentItem: {},
      createStatus: false,
      form: {keys: []},
      nameList: [],
      searchParams: {},
      lineList: [],
      drawerVisible: false,
      processTotal: 0,
      planList: [],
      index: 0,
      allRouteData: [],
      productData: [],
      materialData: [],
      lineListAll: [],
    };
  },
  computed: {
    tableHeight() {
      return window.innerHeight - 400;
    },
  },

  mounted() {
    this.getList();
    this.relevance();
  },
  methods: {
    handleIssue(row) {
      issuePlan(row).then((res) => {
        if (res.code !== 200) {
          this.$Message.warning(res.message);
          return false;
        }
        this.rowChildren({...row, id: row.productionPlanId});
        this.$Message.warning("下发成功");
      });
    },
    handleExpandChange(row, expandedRows) {
      if (expandedRows.includes(row)) {
        this.rowChildren(row);
      } else {
        this.getList();
      }
    },
    rowChildren(row) {
      ProductionPlanDetailApi({planId: row.id}).then((res) => {
        if (res.code !== 200) {
          this.$Message.warning(res.message);
          return false;
        }
        const listGroup = this.list.map((item, index) => {
          if (item.id == row.id) {
            return {...item, children: res.data.records};
          }
          return item;
        });
        this.list = listGroup;
      });
    },

    relevance() {
      lineAll({current: 1, pageSize: 100000}).then((res) => {
        if (res.code === 200) {
          this.lineListAll = res.data.records;
          this.lineList = buildTree(res.data.records);
        }
      }),
          allRouteApi({current: 1, pageSize: 100000}).then((res) => {
            this.allRouteData = res.data.records;
          });
      materialBomApi({current: 1, pageSize: 100000}).then((res) => {
        this.materialData = res.data.records;
      });
      productAllApi({current: 1, pageSize: 100000}).then((res) => {
        this.productData = res.data;
      });
    },

    planDetail(query) {
    },
    drawerClose() {
      this.drawerVisible = false;
    },

    getSearch(arg) {
      this.searchParams = arg[0] || {};
      this.getList();
    },

    async getList() {
      this.isTableVisible = false;
      try {
        const response = await productBaseDataPlanApi({
          ...this.params,
          ...this.searchParams,
        });
        if (response.code === 200) {
          this.list = response.data.records.map((item) => {
            return {...item, children: [], layer: 1, _loading: false};
          });
          this.total = response.data.total;
        } else {
          this.$Message.warning(response.msg);
        }
      } catch (error) {
        this.$Message.error("获取列表失败");
      }
      this.$nextTick(() => {
        this.isTableVisible = true;
      });
    },
    reset() {
      this.params = {pageSize: 20, current: 1};
      this.getList();
    },
    changeNum() {
      this.params.current = 1;
      this.params.pageSize = 20;
      this.getList();
    },
    handleAdd() {
      this.form = {keys: [{}]};
      this.createStatus = true;
    },

    handleImportData() {
      this.importExcelState = true;
    },

    handleAddSubmit() {
      const url = this.form.id ? editBaseDataPlanApi : addBaseDataPlanApi;
      console.log(this.form, "params");
      const planDetail = this.form.keys.map((item) => ({

        productId: item.productId,
        processRouteId: item.processRouteId,
        bomId: item.bomId,
        planCount: Number(item.planCount),
        type: this.form.type,
        status: 0,
      }));

      const params = {
        ...this.form,
        keys: undefined,
        planBeginTime: this.form.planBeginTime
            ? this.$moment(this.form.planBeginTime[0]).format(
                "YYYY-MM-DD HH:mm:ss"
            )
            : "",
        planEndTime: this.form.planBeginTime
            ? this.$moment(this.form.planBeginTime[1]).format(
                "YYYY-MM-DD HH:mm:ss"
            )
            : "",
        status: 0,
        organizationId:
            this.form.organizationId[this.form.organizationId.length - 1],
        productionPlanDetailDTO: planDetail
      };


      url(params)
          .then((res) => {
            if (res.code === 200) {
              this.$Message.success(res.message);
              this.currentItem = {};
              this.createStatus = false;
              this.getList();


            }
          })
          .catch((error) => {
            console.error("Error submitting form:", error);
          });
    },
    handleEditRow(row, type) {
      ProductionPlanDetailApi({planId: row.id}).then((res) => {
        this.form = {
          ...row,
          planBeginTime: [row.planBeginTime, row.planEndTime],
          actualBeginTime: [row.actualBeginTime, row.actualEndTime],
          keys: res.data.records,
        };
        res.data.records.forEach((item, index) => {
          this.keysArray(item.productId, index);
        });
      });

      console.log(this.form);
      this.createStatus = true;
    },
    keysArray(e, index) {
      const allRouteData = this.allRouteData.filter((i) => i.productId === e);
      const materialBom = this.materialData.filter((i) => i.productId === e);
      this.form.keys[index].allRouteData = allRouteData;
      this.form.keys[index].materialBom = materialBom;
    },
    handleDeleteRow(row) {
      this.currentItem = row;
      this.deleteShow = true;
    },
    IsCloseDel(res) {
      this.$Message.success(res.message);
      this.currentItem = {};
      this.deleteShow = false;
      this.getList();
    },
    async handleDeleteSure() {
      const del = await deleteBaseDataPlanApi({ids: [this.currentItem.id]});
      await ProductionPlanDetailApi({
        planId: this.currentItem.id,
      }).then((res) => {
        if (res.data.records.length) {
          const ids = res.data.records.map((i) => i.id);
          deleteProductionPlanDetailApi({ids: ids}).then((res) => {
            this.IsCloseDel(res);
          });
        } else {
          this.IsCloseDel(del);
        }
      });
    },
    changePageNum(val) {
      this.params.current = val;
      this.getList();
    },
    changePageSize(val) {
      this.params.pageSize = val;
      this.getList();
    },
  },
};
</script>

<style scoped>
.tableContent {
}
</style>
